package com.jdyfy.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jdyfy.constant.MessageConstant;
import com.jdyfy.constant.StatusConstant;
import com.jdyfy.dto.RoleUserCountDTO;
import com.jdyfy.dto.UserLoginDTO;
import com.jdyfy.entity.Menu;
import com.jdyfy.entity.Project;
import com.jdyfy.entity.User;
import com.jdyfy.exception.AccountNotFoundException;
import com.jdyfy.exception.PasswordErrorException;
import com.jdyfy.mapper.ProjectMapper;
import com.jdyfy.mapper.RoleMapper;
import com.jdyfy.mapper.RoleMenuMapper;
import com.jdyfy.mapper.UserMapper;
import com.jdyfy.service.MenuService;
import com.jdyfy.service.UserService;
import com.jdyfy.utils.Md5Util;
import com.jdyfy.utils.TokenUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static java.time.LocalDateTime.now;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Resource
    private MenuService menuService;

    /**
     * 员工登录
     *
     * @param userLoginDTO
     * @return
     */
    public User login(UserLoginDTO userLoginDTO) {

        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        User user = userMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (user == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //MD5加密处理
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (user.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            //throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
            return user;
        }
        String token = TokenUtils.genToken(username, password);
        user.setToken(token);

        Long roleId = user.getRoleId();
        //设置用户的菜单列表
        List<Menu> roleMenus = getRoleMenus(roleId);
        user.setMenus(roleMenus);

        user.setLastTime(now());
        userMapper.update(user);
        //3、返回实体对象
        return user;
    }

    /**
     * 获取当前角色所有的菜单
     * @param roleId
     * @return
     */
    private List<Menu> getRoleMenus(Long roleId) {
        //当前角色所有的菜单id集合
        List<Long> menuIds = roleMenuMapper.selectByRoleId(roleId);

        //查出系统所有菜单
        List<Menu> menus = menuService.findMenus();

        //new一个最后筛选完的菜单
        List<Menu> roleMenus = new ArrayList<>();
        //筛选当前用户角色的菜单
        for (Menu menu : menus) {
            //从c菜单中筛选出当前用户拥有的菜单
            if (menuIds.contains(menu.getMenuId())) {
                roleMenus.add(menu);
            }
            List<Menu> children = menu.getChildren();
            //移除children中不在menuIds集合中的元素
            children.removeIf(c -> !menuIds.contains(c.getMenuId()));
        }
        return roleMenus;
    }

    //新增或修改
    public Integer savee(User user){
        if(user.getUserId()==null){ //user没有id,则表示新增
            user.setPassword("e10adc3949ba59abbe56e057f20f883e"); //123456
            return userMapper.insert(user);
        } else { //否则为更新
            return userMapper.update(user);
        }
    }

    //查询所有
    public List<User> findAll(){
        return userMapper.findAll();
    }


    //根据id查询
    public User getByUserId(Long id){
        return userMapper.getByUserId(id);
    }

    //根据用户名查询
    public User getByUsername(String username){
        return userMapper.getByUsername(username);
    }

    //根据名查询
    public User getByName(String name) {
        return userMapper.getByName(name);
    }

    //根据角色id查询角色
    public List<User> getUsersByRoleId(Long roleId) {
        return userMapper.getUsersByRoleId(roleId);
    }

    // 统计角色对应的用户数量
    public List<RoleUserCountDTO> getUserCountByRole() {
        return userMapper.getUserCountByRole();
    }

}
